<template>
  <div class="dynamic-specs">
    <!-- 添加规格按钮 -->
    <el-button 
      @click="addSpec" 
      type="primary" 
      class="add-spec-button"
      :icon="Plus"
    >
      添加规格
    </el-button>

    <!-- 规格列表 -->
    <draggable 
      v-model="specs" 
      item-key="id"
      handle=".drag-handle"
      @end="onDragEnd"
    >
      <template #item="{ element: spec, index: specIndex }">
        <el-card shadow="hover" class="spec-card">
          <div class="spec-header">
            <!-- 拖拽手柄 -->
            <el-icon class="drag-handle">
              <Rank />
            </el-icon>
            
            <!-- 规格名称 -->
            <el-input
              v-model="spec.name"
              placeholder="规格名称（如：重量）"
              clearable
              @change="handleSpecChange(specIndex)"
            />
            
            <!-- 规格操作按钮 -->
            <div class="spec-actions">
              <el-button
                @click="addSpecValue(specIndex)"
                type="primary"
                size="small"
                :icon="Plus"
              >
                添加值
              </el-button>
              <el-button
                @click="removeSpec(specIndex)"
                type="danger"
                size="small"
                :icon="Delete"
              />
            </div>
          </div>

          <!-- 规格值列表 -->
          <draggable
            v-model="spec.values"
            item-key="id"
            handle=".drag-handle"
            @end="onDragEnd"
          >
            <template #item="{ element: value, index: valueIndex }">
              <div class="value-item">
                <el-icon class="drag-handle">
                  <Rank />
                </el-icon>
                
                <el-input
                  v-model="value.valueName"
                  placeholder="规格值（如：1kg）"
                  clearable
                  @change="handleValueChange(specIndex, valueIndex)"
                />
                
                <el-button
                  @click="removeSpecValue(specIndex, valueIndex)"
                  type="danger"
                  text
                  :icon="Delete"
                />
              </div>
            </template>
          </draggable>
        </el-card>
      </template>
    </draggable>
  </div>
</template>

<script setup lang="ts">
import { ref, watch, defineProps, defineEmits } from 'vue'
import { Delete, Plus, Rank } from '@element-plus/icons-vue'
import draggable from 'vuedraggable'

interface SpecValue {
  id: string
  name: string
  valueName: string
}

interface Specification {
  id: string
  name: string
  values: SpecValue[]
}

const props = defineProps({
  modelValue: {
    type: Array as () => Specification[],
    default: () => []
  }
})

const emit = defineEmits(['update:modelValue', 'change'])

const specs = ref<Specification[]>([])

// 初始化数据
watch(() => props.modelValue, (newVal) => {
  if (newVal && newVal.length > 0) {
    specs.value = JSON.parse(JSON.stringify(newVal))
  }
}, { immediate: true })

// 生成唯一ID
const generateId = () => Math.random().toString(36).substring(2, 10)

// 添加新规格
const addSpec = () => {
  const newSpec = {
    id: generateId(),
    name: '',
    values: [{
      id: generateId(),
      name: '',
      valueName: ''
    }]
  }
  specs.value.push(newSpec)
  emitChange()
}

// 删除规格
const removeSpec = (index: number) => {
  specs.value.splice(index, 1)
  emitChange()
}

// 添加规格值
const addSpecValue = (specIndex: number) => {
  specs.value[specIndex].values.push({
    id: generateId(),
    name: '',
    valueName: ''
  })
  emitChange()
}

// 删除规格值
const removeSpecValue = (specIndex: number, valueIndex: number) => {
  specs.value[specIndex].values.splice(valueIndex, 1)
  emitChange()
}

// 规格名称变化处理
const handleSpecChange = (specIndex: number) => {
  const spec = specs.value[specIndex]
  // 自动生成name字段（去除空格和特殊字符）
  if (spec.name && !spec.values[0].name) {
    spec.values.forEach(value => {
      value.name = spec.name.toLowerCase().replace(/\s+/g, '_')
    })
  }
  emitChange()
}

// 规格值变化处理
const handleValueChange = (specIndex: number, valueIndex: number) => {
  const value = specs.value[specIndex].values[valueIndex]
  // 自动生成name字段
  if (value.valueName && !value.name) {
    value.name = value.valueName.toLowerCase().replace(/\s+/g, '_')
  }
  emitChange()
}

// 拖拽结束处理
const onDragEnd = () => {
  emitChange()
}

// 触发更新事件
const emitChange = () => {
  emit('update:modelValue', specs.value)
  emit('change', specs.value)
}
</script>

<style scoped lang="scss">
.dynamic-specs {
  .add-spec-button {
    margin-bottom: 16px;
  }

  .spec-card {
    margin-bottom: 16px;
    padding: 12px;
    
    .spec-header {
      display: flex;
      align-items: center;
      margin-bottom: 12px;
      
      .drag-handle {
        margin-right: 8px;
        cursor: move;
        color: var(--el-text-color-secondary);
      }
      
      .el-input {
        flex: 1;
        margin-right: 12px;
      }
      
      .spec-actions {
        flex-shrink: 0;
      }
    }
    
    .value-item {
      display: flex;
      align-items: center;
      margin-bottom: 8px;
      
      .drag-handle {
        margin-right: 8px;
        cursor: move;
        color: var(--el-text-color-secondary);
      }
      
      .el-input {
        flex: 1;
        margin-right: 12px;
      }
    }
  }
}
</style>